/**
 *  File: BeanConvertUtil.java
 *  Description:
 *  Copyright 2004-2009 99Bill Corporation. All rights reserved.
 *  2009-7-28      winters.he      Changes
 *  
 *
 */
package com.fdl.common.utils;

import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * Bean属性转换工具类
 * @project: hb-intra
 * @Date:2010-7-29
 * @version  1.0
 * @Company: 33e9
 * @author zhangYong.huang
 */
public class BeanConvertUtil {
	private static final Log log = LogFactory
			.getLog(BeanConvertUtil.class);

	/**
	 * 把Bean数据转换为另外一个类的对象中.
	 * @param targetClass 目标对象的类,必须有public 的 无参数的 construct method.
	 * @param sourceObject 数据源
	 * @return 数据目标
	 */
	public static Object convert(Class targetClass, Object sourceObject) {
		if (sourceObject == null) {
			return null;
		}
		try {
			Object targetObject = targetClass.newInstance();
			BeanUtils.copyProperties(sourceObject, targetObject);
			return targetObject;
		} catch (InstantiationException e) {
			log.error("Can't create Instance of Class:" + targetClass, e);
		} catch (IllegalAccessException e) {
			log.error("Can't access construct method of Class:"
					+ targetClass, e);
		}
		return null;
	}
	
	/**
	 * 把Bean数据转换为另外一个类的对象集合中.
	 * @param targetClass 目标对象的类,必须有public 的 无参数的 construct method.
	 * @param sources 数据源
	 * @return 数据目标
	 */
	public static Collection convert(Class targetClass, Collection sources){
		if (sources == null || sources.isEmpty()) {
			return null;
		}
		try {
			Collection targets = sources.getClass().newInstance();
			for (Object sourceObject : sources) {
				Object targetObject = targetClass.newInstance();
				BeanUtils.copyProperties(sourceObject, targetObject);
				targets.add(targetObject);
			}
			return targets;
		} catch (InstantiationException e) {
			log.error("Can't create Instance of Class:" + targetClass, e);
		} catch (IllegalAccessException e) {
			log.error("Can't access construct method of Class:"
					+ targetClass, e);
		}
		return null;
	}
	
	/**
	 * 将指定对象转换为Map<String,String>对象.
	 * 
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> bean2Map(Object obj) {
		if (null == obj) {
			return null;
		}
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		BeanWrapper wrapper = new BeanWrapperImpl(obj);
		PropertyDescriptor[] propertys = wrapper.getPropertyDescriptors();
		for (int i = 0; i < propertys.length; i++) {
			String propertyName = propertys[i].getName();
			Object value = wrapper.getPropertyValue(propertyName);
			if (value != null) {
				map.put(propertyName, value);
			}
		}
		map.remove("class");
		return map;
	}
	
}
